<template>
	<view class="container">
		<view @click="handleChooseImage" class="brand">
			<view style="position: relative;" class="image_175 round">
				<image v-if="form.avatarUrl" :src="form.avatarUrl" mode="scaleToFill" class=" round image_175"></image>
				<image v-else class="image_175 round bg-gray" src="/static/logo.jpg"></image>
				<view style="position: absolute;bottom: 0px;width: 100%;line-height: 1.5rem;"
					class="text-center text-size-10 text-white text-bold">点击上传</view>
			</view>
			<view class="username margin-top-sm">{{ form.nickname ? form.nickname : '暂无昵称' }}</view>
		</view>
		<view class="user-form">
			<list-cell line-right padding="30rpx">
				<view class="form-item">
					<view class="label">昵称</view>
					<input type="text" placeholder="请输入昵称" v-model="form.nickname" />
				</view>
			</list-cell>
			<list-cell line-right padding="30rpx">
				<view class="form-item">
					<view class="label">手机号码</view>
					<input type="text" placeholder="请输入手机号" v-model="form.phone" />
					<button type="default" plain class="text-size-12 sm" @tap="handleShowBindPhone">授权手机</button>
	<!-- 				<button type="default" plain class="text-size-12 sm" @tap="showTelphoneModal">更换手机</button> -->
				</view>
			</list-cell>
			<list-cell line-right padding="30rpx">
				<view class="form-item">
					<view class="label">性别</view>
					<view class="radio" @tap="form.gender = 1">
						<image v-if="form.gender==1" src="/static/images/common/round-black-selected.png">
						</image>
						<image v-else src="/static/images/common/gouxuankuang.png">
						</image>
						<view>男</view>
					</view>
					<view class="radio" @tap="form.gender = 2">
						<image v-if="form.gender==2" src="/static/images/common/round-black-selected.png">
						</image>
						<image v-else src="/static/images/common/gouxuankuang.png">
						</image>
						<view>女</view>
					</view>
				</view>
			</list-cell>
			<list-cell line-right padding="30rpx" last>
				<view class="form-item">
					<view class="label">生日</view>
					<picker class="flex-fill" mode="date" :value="form.birthday" @change="handleBirthdayChange">
						<view>{{ form.birthday ? form.birthday : '请选择生日' }}</view>
					</picker>
				</view>
			</list-cell>
		</view>

		<view class="save-btn">
			<button type="info" class="cu-btn line-grey lg" @click="handleSave">保存</button>
			<button type="info" class="cu-btn line-grey lg margin-top-sm" @click="handleLogoOut">退出登录</button>
		</view>

		<modal :show="telphoneModalVisible" custom padding="40rpx 30rpx">
			<view class="telphone-modal">
				<view class="header">
					<view>温馨提示</view>
					<image src="/static/images/common/closex.png" class="close-icon" @tap="closeTelphoneModal"></image>
				</view>
				<view class="tips">为保障您正常使用源社区GO小程序，请在绑定前确定新手机号未绑定源社区GO。</view>
				<view class="telphone-form">
					<list-cell padding="30rpx 0">
						<view class="telphone-input">
							<view class="prefix">+86</view>
							<input type="text" v-model="telphoneForm.phone" placeholder="请填写有效手机号码"
								placeholder-class="font-size-base text-color-assist" />
						</view>
					</list-cell>
					<list-cell padding="30rpx 0">
						<view class="verfiycode-input">
							<input type="text" v-model="telphoneForm.verifyCode" placeholder="6位数字验证码"
								placeholder-class="font-size-base text-color-assist" />
							<view class="countdown"
								:class="{ 'text-color-assist': !countdown, 'text-color-base': countdown }"
								@tap="getVerifyCode">
								{{ !countdown ? '获取验证码' : countdown + '秒可获取' }}
							</view>
						</view>
					</list-cell>
				</view>
				<view class="padding flex flex-direction">
					<button type="primary" @tap="closeTelphoneModal">确认</button>
				</view>
			</view>
		</modal>
		<cu-modal @action="handleBindPhone" tag="AuthorizationModal" :modalName="visible"></cu-modal>
	</view>
</template>

<script setup lang="ts">
	import listCell from '@/components/list-cell/list-cell.vue';
	import modal from '@/components/modal/modal.vue';
	import cuModal from '@/components/cu-modal.vue';
	import { ref } from 'vue';
	import { onShow, onLoad, onPullDownRefresh } from '@dcloudio/uni-app';
	import { useSettingStore } from '@/stores/index';
	import { accountInfo, setUserinfo } from '@/common/api/user';
	import { verifyCode,logout,login } from '@/common/api/login';
	import { uploadFile } from '@/common/utils/http';
	const setting = useSettingStore();
	const form = ref({ birthday: '', address: '', avatarUrl: '', email: '', gender: '', msgNum: '', nickname: '', phone: '', realName: '', username: '' });
	const telphoneModalVisible = ref(false);
	const telphoneForm = ref({
		phone: '',
		verifyCode: ''
	});
	const visible = ref('')
	const handleBindPhone = async (e : any) => {
		visible.value = '';
		if (!e) {
			uni.showToast({
				title: '授权失败',
				duration: 2000
			});
			setTimeout(()=>{
				uni.hideToast();
			},1000)
			return;
		}
		if (!e.detail) {
			uni.showToast({
				title: '授权失败',
				duration: 2000
			});
			setTimeout(()=>{
				uni.hideToast();
			},1000)
			return;
		}
		if (!e.detail.code) {
			uni.showToast({
				title: '授权失败',
				duration: 2000
			});
			setTimeout(()=>{
				uni.hideToast();
			},1000)
			return;
		}
		handleWxLogin(e.detail.code)
	};
	const handleShowBindPhone = () => {
		visible.value = 'AuthorizationModal';
	};
	/**
	 * 微信授权code
	 */
	const handleWxLogin = (code : any) => {
		uni.login({
			provider: 'weixin',
			success: res => {
				onWxLogin(res.code, code);
			}
		});
	};
	const onWxLogin = (code : string, phonecode : string) => {
		//debugger
		login({
			loginMethod: 'wechat',
			wechatCode: code,
			phoneCode: phonecode
		}).then((res : any) => {
			uni.hideLoading();
			if (res.code == 1000) {
				setting.onLogin(res.data.token);
				setting.setOpenId(res.data.openId)
				setting.token = res.data.token;
				onUser();
			} else {
				uni.showToast({
					title: '登录失败',
					duration: 2000
				});
			}
		});
	};
	const countdown = ref(0);
	const handleBirthdayChange = ({ target: { value } }) => {
		form.value.birthday = value;
	};
	const showTelphoneModal = () => {
		telphoneModalVisible.value = true;
	};
	const closeTelphoneModal = () => {
		telphoneModalVisible.value = false;
		telphoneForm.value = {
			phone: '',
			verifyCode: ''
		};
	};
	const handleSave = async () => {
		//form.value.gender = form.value.gender ? '1' : '2';
		const res : any = await setUserinfo(form.value);
		if (res.code == 1000) {
			uni.showModal({
				title: '修改成功'
			});
			onUser();
		} else {
			uni.showModal({
				title: res.msg
			});
		}
	};
	const handleChooseImage = (e : any) => {
		uni.chooseImage({
			count: 1, //默认9
			sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
			sourceType: ['album'], //从相册选择
			success: (res : any) => {
				if (res.tempFilePaths.length > 0) {
					onUploadFiles(res.tempFilePaths);
				}
			}
		});
	};
	/**
	 * 点击事件
	 */
	const onUploadFiles = async (tempFilePaths : any) => {
		const res : any = await uploadFile('/api/file/upload', {}, tempFilePaths[0]);
		if (res.code == 1000) {
			let array = res.data;
			if (array && array.length > 0) {
				form.value.avatarUrl = res.data[0].url;
			}
		} else {
			uni.showModal({
				title: res.msg
			});
		}
	};
	const getVerifyCode = async () => {
		if (countdown.value) return;
		if (!telphoneForm.value.phone) {
			uni.showToast({
				title: '请填写手机号码',
				icon: 'none'
			});
			return;
		}

		countdown.value = 60;
		const res : any = await verifyCode({ phone: telphoneForm.value.phone })
		if (res.code == 1000) {
			let interval = setInterval(() => {
				if (!countdown.value) {
					clearInterval(interval);
					return;
				}
				countdown.value -= 1;
			}, 1000);
		}

	};
	const onUser = async () => {
		const res : any = await accountInfo({});
		if (res.code == 1000) {
			form.value = res.data;
			form.value.birthday = '';
		} else {
			uni.showModal({
				title: res.msg
			});
		}
	};
	/**
		 * 点击事件
		 */
	const handleLogoOut = () => {
		setting.logout();
		logout();
		uni.switchTab({
			url: '/pages/index/index'
		});
	};
	onLoad(() => {
		onUser();
	});
</script>

<style lang="scss" scoped>
	.brand {
		background-color: $bg-color-white;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 40rpx 0;
		margin-bottom: 20rpx;

		.avatar {
			width: 200rpx;
			height: 200rpx;
			border-radius: 100%;
			margin-bottom: 30rpx;
		}

		.username {
			color: $font-size-medium;
			font-weight: bold;
		}
	}

	.user-form {
		.form-item {
			width: 100%;
			display: flex;
			align-items: center;

			.label {
				width: 160rpx;
			}

			input {
				flex: 1;
			}

			.radio {
				display: flex;
				margin-right: 50rpx;

				image {
					width: 40rpx;
					height: 40rpx;
					margin-right: 20rpx;
				}
			}
		}
	}

	.save-btn {
		padding: 0 30rpx;
		margin-top: 60rpx;

		button {
			width: 100%;
			font-size: $font-size-extra-lg;
		}
	}

	.telphone-modal {
		.header {
			display: flex;
			align-items: center;
			justify-content: center;
			position: relative;
			font-size: $font-size-extra-lg;
			font-weight: bold;
			margin-bottom: 30rpx;

			.close-icon {
				width: 60rpx;
				height: 60rpx;
				position: absolute;
				right: 0;
			}
		}

		.tips {
			color: $text-color-grey;
			line-height: 1.2rem;
			margin-bottom: 50rpx;
		}

		.telphone-form {
			font-size: $font-size-base;

			.telphone-input {
				width: 100%;
				display: flex;
				align-items: center;

				.prefix {
					color: $color-primary;
					display: flex;
					align-items: center;
					padding-right: 20rpx;
					position: relative;
					margin-right: 10rpx;

					&::after {
						content: ' ';
						position: absolute;
						width: 4rpx;
						background-color: $border-color;
					}
				}

				input {
					flex: 1;
				}
			}

			.verfiycode-input {
				width: 100%;
				display: flex;
				align-items: center;
				justify-content: space-between;

				.countdown {
					font-size: $font-size-base;
				}
			}
		}

		.footer {
			margin-top: 30rpx;

			button {
				font-size: $font-size-lg;
			}
		}
	}
</style>